<?php
namespace Todo\Model\Sys;

use Todo\Service\LoginService;
use Org\Util\String;

class UserModel extends SysBaseModel
{
    protected $_validate = array(
        array('account', 'require', '请输入用户账号', 0, 'unique', 1),
        array('nickname', 'require', '请输入用户昵称'),
    );

    protected $_auto = array(
        array('photo', '', self::MODEL_INSERT),
        array('is_del', 0, self::MODEL_INSERT),
        array('login_count', 0, self::MODEL_INSERT),
        array('last_time', 0, self::MODEL_INSERT),
        array('last_ip', '', self::MODEL_INSERT),
        array('create_time', 'time', self::MODEL_INSERT, 'function'),
        array('update_time', 'time', self::MODEL_BOTH, 'function'),
        array('password', '_password', self::MODEL_INSERT, 'callback'),
        array('salt', '_salt', self::MODEL_INSERT, 'callback')
    );
    
    protected function _salt(){
        if(!$this->salt) $this->salt =  String::randString(6);
        return $this->salt;
    }
    protected function _password(){
        $this->_salt();
        $password = I('post.password');
        if(!$password) $password = C('DEFAULT_PASSWORD');
        return LoginService::getInstance()->encrypt($password,  $this->salt);
    }

    /**
     * 格式化数据
     * @param array $info 一条数据对象
     * @param array $fields
     */
    public function format(&$info, $fields = array('status')){
        if(!$fields) return;

        if(!is_array($fields)) $fields = explode(',', $fields);
        foreach($fields as $field){
            if($field == 'status') $info['status_text'] = ($info['status'] == 1 ? '启用' : '禁用');
            if($field == 'depart') {
                $departInfo = D('Todo/Sys/Depart')->cache('depart_'.$info['depart_id'])->where(array('id'=>$info['depart_id']))->find();
                $info['depart_text']  = $departInfo ? $departInfo['title'] : '其它';
            }
            if($field == 'identity') {
                $identityIds = M('sys_user_identity')->where(array('user_id'=>$info['id']))->getField('identity_id',true);
                if($identityIds) $info['identity_text'] = D('Todo/Sys/Identity')->where(array('id'=>array('in', $identityIds)))->getField('title',',');
            }
        }
    }

    /**
     * 添加用户完成后操作
     * @param $data
     * @param $options
     */
    protected function _after_insert($data,$options) {
        $idenIds = I('post.identity_id');
        if(!is_array($idenIds)) $idenIds = explode(',', $idenIds);
        $uiModel = M('sys_user_identity');
        $urModel = M('sys_user_role');
        foreach($idenIds as $idenId){
            $uiModel->add(array('user_id'=>$data['id'], 'identity_id'=>$idenId));
            $roleId = D('Todo/Sys/Identity')->keyFind($idenId, 'role_id');
            if($roleId) $urModel->add(array('user_id'=>$data['id'], 'role_id'=>$roleId));
        }

        $roleIds = I('post.role_id');
        if(!is_array($roleIds)) $roleIds = explode(',', $roleIds);
        foreach($roleIds as $roleId){
            $ur = array('user_id'=>$data['id'], 'role_id'=>$roleId);
            if(!$urModel->where($ur)->find()) $urModel->add($ur);
        }
    }

    protected function _after_update($data,$options) {
        $idenIds = I('post.identity_id');
        $roleIds = I('post.role_id');
        if(!$idenIds || !$roleIds) return;

        if(!is_array($idenIds)) $idenIds = explode(',', $idenIds);
        $uiModel = M('sys_user_identity');
        $uiModel->where(array('user_id'=>$data['id']))->delete();
        $urModel = M('sys_user_role');
        $urModel->where(array('user_id'=>$data['id']))->delete();
        foreach($idenIds as $idenId){
            if(!$idenId) continue;
            $ui = array('user_id'=>$data['id'], 'identity_id'=>$idenId);
            if(!$uiModel->where($ui)->find()) $uiModel->add($ui);

            $roleId = D('Todo/Sys/Identity')->keyFind($idenId, 'role_id');
            if(!$roleId) continue;
            $ur = array('user_id'=>$data['id'], 'role_id'=>$roleId);
            if(!$urModel->where($ur)->find()) $urModel->add($ur);
        }

        if(!is_array($roleIds)) $roleIds = explode(',', $roleIds);
        foreach($roleIds as $roleId){
            if(!$roleId) continue;
            $ur = array('user_id'=>$data['id'], 'role_id'=>$roleId);
            if(!$urModel->where($ur)->find()) $urModel->add($ur);
        }

    }

    /**
     * 查询用户身份
     * @param $userId
     * @return $array
     */
    public function getUserIdenIds($userId){
        return M('sys_user_identity')->where(array('user_id'=>$userId))->getField('identity_id',true);
    }

    /**
     * 查询用户角色
     * @param $userId
     */
    public function getUserRoleIds($userId){
        return M('sys_user_role')->where(array('user_id'=>$userId))->getField('role_id',true);
    }

    /**
     * 导入用户，成功返回行数，失败返回false
     * @param array $list 数据列表
     * @param int $skip 路过的行数，一般为两行，第一行说明，第二行标题
     * @return int|false
     */
    public function import($list, $skip=2){
        $lines = 0;
        $this->startTrans();
        $depart = new DepartModel();
        $identity = new IdentityModel();
        foreach ($list as $k => $row){
            if($k <= $skip) continue;
            $lines ++;
            $data['account'] = $row[0]; //账号
            $data['nickname'] = $row[1]; //昵称
            $data['phone'] = $row[4]; //手机
            $data['email'] = $row[5]; //邮箱
            //部门
            $departName = $row[2];
            $data['depart_id'] = $depart->findOne(array('title'=>$departName), 'id');
            //身份
            $idenName = $row[3];
            $data['identity_id'] = $identity->findOne(array('title'=>$idenName), 'id');
            $_POST = $data;
            if($this->insert() == false){
                $this->rollback();
                $this->error = '第'. $lines. '行发生错误:'. $this->getError();
                return false;
            }
            unset($data, $_POST);
        }
        $this->commit();
        return $lines;
    }
}